<?php
namespace control;
class toolOverhaulOutClass extends adIndexClass
{
    private const page        = 'toolOverhaulOut';
    private const table       = 'tool_overhaul';
    private const tableMx     = 'tool_overhaul_detail';
    private const tableRecord = 'inventory_record';
    private const title       = '工具检修出库单';
    private const state       = [1=>'已确认',0=>'草稿'];
    private const maintenanceStatus       = [1=>'部分检修', 2=>'检修完成',0=>'检修中'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {

        switch ($fun) {
            case 'toolOverhaulRecordSearch':
                $tr = [
                    'orderNo'          => [
                        'name'  => '{l.toolOverhaul.homeSearch.orderNo}',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'type' => [
                        'name'  => '{l.toolOverhaul.edit.type}',
                        'width' => 200,
                    ],
                    'code'  => [
                        'name'  => '{l.toolOverhaul.edit.code}',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'name'  => [
                        'name'  => '{l.toolOverhaul.edit.name}',
                        'width' => 200,
                    ],
                    'unit'  => [
                        'name'  => '{l.toolOverhaul.edit.unit}',
                        'width' => 200,
                    ],
                    'num'         => [
                        'name'  => '{l.toolOverhaul.edit.num}',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'return_num'          => [
                        'name'  => '{l.toolOverhaul.edit.return_num}',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'not_return_num'          => [
                        'name'  => '{l.toolOverhaul.edit.not_return_num}',
                        'width' => 200,
                    ]
                ];
                break;
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '{l.toolOverhaul.homeSearch.orderNo}',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'applicant' => [
                        'name'  => '{l.toolOverhaul.homeSearch.applicant}',
                        'width' => 200,
                    ],
                    'orderDate'  => [
                        'name'  => '{l.toolOverhaul.homeSearch.orderDate}',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'factory'  => [
                        'name'  => '{l.toolOverhaul.homeSearch.factory}',
                        'width' => 200,
                    ],
                    'num'  => [
                        'name'  => '{l.toolOverhaul.homeSearch.num}',
                        'width' => 200,
                    ],
                    'money'         => [
                        'name'  => '{l.toolOverhaul.homeSearch.money}',
                        'width' => 200,
                    ],
                    'return_num'          => [
                        'name'  => '{l.toolOverhaul.homeSearch.return_num}',
                        'width' => 200,
                    ],
                    'text'          => [
                        'name'  => '{l.toolOverhaul.homeSearch.text}',
                        'width' => 200,
                    ],
                    'state'          => [
                        'name'  => '{l.toolOverhaul.homeSearch.state}',
                        'width' => 200,
                    ],
                    'maintenance_status'          => [
                        'name'  => '{l.toolOverhaul.homeSearch.maintenanceStatus}',
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('toolOverhaul.home.orderNo') => text(array("name" => "orderNo")),
                    L('toolOverhaul.home.applicant')   => text(array("name" => "applicant")),
                    L('toolOverhaul.homeSearch.orderDate') => text(['name' => 'orderDate', 'laydate' => ['range' => '~', 'type' => 'date']]),
                ],
                [
                    L('toolOverhaul.home.state')  => select(["name" => "state", 'option' => self::state]),
                    L('toolOverhaul.home.maintenanceStatus') => select(["name" => "maintenanceStatus", 'option' => self::maintenanceStatus]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . L('toolOverhaul.homeSearch.detail') . "','" . $url . "&fun=edit')\" class='spanButton'>".L('toolOverhaul.homeSearch.new')."</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">".L('toolOverhaul.homeSearch.del')."</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //查询结果
        $where = " coid = '" . self::$coid . "' and classify = 0 ";
        $equal = [
            'state'  => $this->post('state'),
            'maintenanceStatus'  => $this->post('maintenanceStatus'),
        ];
        $like  = [
            'orderNo' => $this->post('orderNo'),
        ];
        //生成查询语句
        $where .= search([
            "="    => $equal,
            "like" => $like,
        ]);
        if ($this->post('orderDate')) {
            $where .= self::timeComparison($this->post('orderDate'), 'date', 'orderDate');
        }
        if($this->post('applicant')){
            $where .= " and applicant in (select stid from staff where name like '%".$this->post('applicant')."%') ";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page    = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        $_SESSION[self::page]['sql'] = $page['sql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        $isPrint  = $this->power(static::page, "print");
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = [
                "box"    => ["name" => "listId", "value" => $array['id'],],
                "detail" => ["title" => L('toolOverhaul.homeSearch.detail'), "click" => "newIframe('" . L('toolOverhaul.homeSearch.detail') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')",],
                "edit"   => ($array['state'] == '草稿') ? ["title" => L('toolOverhaul.homeSearch.edit'), "click" => "newIframe('" . L('toolOverhaul.homeSearch.detail') . "','" . $url . "&fun=edit&id=" . $array['id'] . "')",] : [],
                'print'  => ($isPrint === true) ? ['title' => L('outStockExec.homeListSearch.print'), 'click' => "window.open('" . root . "control/adIndex.html?cla=" . static::page . "&fun=printPage&id={$array['id']}')"] : [],
            ];
            $collection = find(array(
                "table"=>self::tableMx,
                "single"=>"orderId = '".$array['id']."'",
                "field"=>" IFNULL(sum(num),0) as num,IFNULL(sum(money),0) as money,IFNULL(sum(return_num),0) as return_num "
            ));
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'applicant':
                        $row[] = self::findStaff($array['applicant']);
                        break;
                    case 'num':
                        $row[] = self::lostZero($collection['num'],'numPrecision');
                        break;
                    case 'money':
                        $row[] = self::lostZero($collection['money']);
                        break;
                    case 'return_num':
                        $row[] = self::lostZero($collection['return_num'],'numPrecision');
                        break;
                    case 'state':
                        $row[] = self::state[$array['state']];
                        break;
                    case 'maintenance_status':
                        $row[] = self::maintenanceStatus[$array['maintenance_status']];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::tableMx,
            'single' => "orderId in (select id from ".self::table." where {$where})",
            'field'  => "IFNULL(sum(num),0) as num,IFNULL(sum(money),0) as money,IFNULL(sum(return_num),0) as return_num",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
            'money'   => self::lostZero($totalQuery['money'], 'numPrecision'),
            'return_num' => self::lostZero($totalQuery['return_num'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }
    /**
     * 编辑页
     *
     * @return string
     */
    public function edit(): string
    {
        $id       = $this->get('id');
        $info     = query(self::table, " coid = '" . self::$coid . "' AND id = '" . $id . "' ");
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name"  => L('toolOverhaul.edit.save'),
            "type"  => "点击事件",
            "title" => L('toolOverhaul.edit.save'),
            'fun'   => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
        ];
        $tr[]     = ['', '{l.toolOverhaul.edit.code}', '{l.toolOverhaul.edit.name}', '{l.toolOverhaul.edit.model}', '{l.toolOverhaul.edit.unit}', '<div class="warehouse">' . '{l.toolOverhaul.edit.warehouse}' . self::chooseWarehouse(callback: 'getPosition') . '</div>', '{l.toolOverhaul.edit.position}', '{l.toolOverhaul.edit.batch}', '{l.toolOverhaul.edit.inventory}', '{l.toolOverhaul.edit.type}', '{l.toolOverhaul.edit.num}', '{l.toolOverhaul.edit.price}', '{l.toolOverhaul.edit.money}'];
        $result   = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
        $totalArr = ['stock'=>0];
        foreach ((array)$result['array'] as $k=>$array) {
            $material    = query('material', " id = '$array[materialId]'");
            $position = selectMultiple([
                "name" => "positionId[]",
                'option' => self::positionOption($material['id'],$array['warehouseId']),
                'title' => L('toolOverhaul.edit.choice'),
                'change' => 'getBatch',
                'value' => $array['positionId']
            ]);
            $batch = selectMultiple([
                "name" => "batch[]",
                'option' => self::getBatchOption($material['id'], $array['warehouseId'], $array['positionId']),
                'title' => L('toolOverhaul.edit.choice'),
                'change' => 'getStock',
                'value' => $array['batch']
            ]);
            $stock = inventoryBalanceClass::inventoryNum($array['materialId'], $array['warehouseId'], $array['positionId'], $array['batch']);
            $tr[]        =
                [
                    componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
                    hidden(['name' => 'mxId[]', 'value' => $array['id']]) .
                    hidden(['name' => 'materialId[]', 'value' => $array['materialId'],]),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    select(array(
                        'name' => 'warehouseId[]',
                        'option' => self::warehouseOption($material['id']),
                        'change' => 'getPosition',
                        'title' => L('toolOverhaul.edit.warehouse'),
                        'value' => $array['warehouseId']
                    )),
                    "<span class='position'>$position</span>",
                    "<span class='batch'>$batch</span>",
                    "<span class='stock'>$stock</span>",
                    select(["name" => "type[]", 'option' => explode('，',para('maintenancestateType')), 'value' => $array['type'], 'title' => '{l.toolOverhaul.edit.type}']),
                    text(['name' => 'num[]', 'blur' => 'countMoney', 'value' => self::lostZero($array['num'],'numPrecision'), 'other' => self::digitalFiltering('numPrecision')]),
                    text(['name' => 'price[]', 'blur' => 'countMoney', 'value' => self::lostZero($array['price'],'numPrecision'), 'other' => self::digitalFiltering('pricePrecision')]),
                    text(['name' => 'money[]', 'blur' => 'countMoney', 'value' => self::lostZero($array['money']), 'other' => self::digitalFiltering()]),
                ];
            $totalArr['stock'] += $stock;
        }
        $total = [
            8 => "<span id='total_stock'>".self::lostZero($totalArr['stock'],'numPrecision')."</span>",
            10 => "<span id='total_num'>".self::lostZero(array_sum(array_column($result['array'],'num')),'numPrecision')."</span>",
            12 => "<span id='total_money'>".self::lostZero(array_sum(array_column($result['array'],'money')))."</span>",
        ];
        $list  = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total));
        $page  = self::page;
        $but = "<span class='smallButton' onclick=\"layer('{$this->get('cla')}','addMx', $('form[name={$page}EditForm]').serialize())\">".L('toolOverhaul.edit.choiceMaterial')."</span>";
        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . L('toolOverhaul.edit.factory')."：" => text(['name' => "factory", 'class' => 'text', 'value' => $info['factory']]),
                    must . L('toolOverhaul.edit.orderDate')."：" => text(["name" => "orderDate", 'laydate' => [], "value" => $info['orderDate'] ?: $this->date]),
                    must . L('toolOverhaul.edit.applicant')."：" => selectMultiple(["name" => "applicant", "value" => $info['applicant'], 'table' => "staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'title' => L('toolOverhaul.edit.choice')]),
                ],
                [
                    L('toolOverhaul.edit.text') => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => L('toolOverhaul.edit.overhaulMx'),
            'button' => $but,
            'html' => $list,
        ]);
        $data['html'] = $this->pageEdit([
            "html"  => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $cla = self::page;
        $data['html'] .= <<<efo
<script>
function addRow(){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
        $("#materialTable tbody").append(res.html);
        resetNumber($("#materialTable"))
    },'json');
}
//根据仓库获取库位
function getPosition(e){
    let warehouseId = e.value;
    let materialId = $(e).parent().parent().find("[name='materialId[]']").val();
    $.post(root+'control/adIndex.html?cla={$cla}&fun=getPosition',{warehouseId:warehouseId,materialId:materialId},function(res) {
          $(e).parent().parent().find(".position").html(res.position);
    },'json');
}
//根据库位获取批次
function getBatch(e){
    let positionId = e.value;
    let par = $(e).parents("tr")
    let warehouseId = par.find("[name='warehouseId[]']").val();
    let materialId = par.find("[name='materialId[]']").val();
    $.post(root+'control/adIndex.html?cla={$cla}&fun=getBatch',{positionId:positionId,warehouseId:warehouseId,materialId:materialId},function(res) {
          par.find(".batch").html(res.batch);
    },'json');
}
//根据批次获取库存
function getStock(e){
    let batch = e.value;
    let par = $(e).parents("tr")
    let positionId = par.find("[name='positionId[]']").val();
    let warehouseId = par.find("[name='warehouseId[]']").val();
    let materialId = par.find("[name='materialId[]']").val();
    $.post(root+'control/adIndex.html?cla={$cla}&fun=getStock',{warehouseId:warehouseId,positionId:positionId,materialId:materialId,batch:batch},function(res) {
          par.find(".stock").html(res.stock);
          calculateTotal()
    },'json');
}
function countMoney(e) {
    let currentKey = $(e).attr('name')
    let par = $(e).parent().parent()
    let numNode = par.find("[name='num[]']")
    let priceNode = par.find("[name='price[]']")
    let moneyNode = par.find("[name='money[]']")
    let num = numNode.val()*1
    let price = priceNode.val()*1
    let money = moneyNode.val()*1
    if(currentKey === 'num[]'){
        moneyNode.val((num * price).toFixed(amountPrecision)).trigger('input')
    }else if(currentKey === 'price[]'){
        moneyNode.val((num * price).toFixed(amountPrecision)).trigger('input')
    }else if(currentKey === 'money[]'){
        if(num > 0){
            priceNode.val((money / num).toFixed(publicSettings.pricePrecision.num)).trigger('input')
        }else if(price > 0){
            numNode.val((money / price).toFixed(publicSettings.numPrecision.num))
        }
    }
    calculateTotal()
}
//计算总数量
function calculateTotal(){
    let table = $('.editList')
    let stock = 0,
    num = 0,
    money = 0
    table.find("[name='num[]']").each(function(index){
        if($(this).val()){
          num+=Number($(this).val());
        }
        var moneyValue = table.find("[name='money[]']").eq(index).val()
        if(moneyValue){
            money+=Number(moneyValue);
        }
        var stockText = table.find(".stock").eq(index).text()
        if(stockText){
            stock+=Number(stockText);
        }
    })
    $("#total_stock").text(stock.toFixed(publicSettings.numPrecision.num));
    $("#total_num").text(num.toFixed(publicSettings.numPrecision.num));
    $("#total_money").text(money.toFixed(amountPrecision));
}
</script>

efo;
        //返回
        return $this->tab($data);
    }
    /**
     * 获取主单位
     */
    public static function getMainUnit($materialId): string
    {
        $material = query('material', " id = '$materialId'",'unit');
        return $material['unit'];
    }
    /**
     * 获取仓库选择下拉（带库存数量）
     */
    public static function warehouseOption($materialId, $unit = ''): array
    {
        $where        = " coid = '" . self::$coid . "' and state = '启用' ".self::getWarehouseSql()." order by time desc ";
        $result = find([
            'table' => 'warehouse',
            'field' => 'id,name',
            'where' => $where,
        ]);
        $option  = [];
        $mainUnit = self::getMainUnit($materialId);
        if (is_array($result['array'])) {
            foreach ((array)$result['array'] as $val) {
                $inventory = inventoryBalanceClass::inventoryNum($materialId, $val['id']);
                if($unit) {
                    $inventory = machiningOrderClass::material_num_change($materialId, $mainUnit, $unit, $inventory);
                }
                $option[$val['id']] = $val['name']."（".$inventory."）";
            }
        }
        return $option;
    }

    /** 库位选择
     *
     * @param string $materialId
     * @param string $warehouseId
     * @param string $unit
     * @return array
     */
    public static function positionOption(string $materialId, string $warehouseId, string $unit = ''): array
    {
        $where            = "";
        $and              = " AND a.coid = '" . self::$coid . "' ";
        $like             = [];
        $equal            = [
            'a.materialId' => $materialId,
            'a.warehouseId' => $warehouseId,
        ];
        $where            .= search([
                "like" => $like,
                "="    => $equal,
            ]) . $and;
        $fieldArr         = self::resolveField([
            'field' => 'a.`positionId`, b.name, SUM(a.num) as num',
            'group' => 'a.positionId',
        ]);
        $where            .= $fieldArr['group'] . " having sum(a.num)>0";
        $inventory_record = find([
            "table" => 'inventory_record as a join warehouse_position as b on a.positionId = b.id',
            'field' => $fieldArr['field'],
            "where" => $where . " order by sum(a.num) desc "
        ]);
        $option = [];
        $mainUnit = self::getMainUnit($materialId);
        foreach ((array)$inventory_record['array'] as $val) {
            if($unit) {
                $val['num'] = machiningOrderClass::material_num_change($materialId, $mainUnit, $unit, $val['num']);
            }
            $option[$val['positionId']] = $val['name']."（".self::lostZero($val['num'],'numPrecision')."）";
        }
        // 无库存库位
        $no_inventory = find([
            "table" => 'warehouse_position',
            'field' => "id,concat(name,'（0）') as name",
            "where" => " coid = '" . self::$coid . "' and orderId = '".$warehouseId."' and id not in ('".implode("','",array_keys($option))."') order by list "
        ]);
        return array_merge($option,count($no_inventory['array'])>0?array_column($no_inventory['array'],'name','id'):[]);
    }

    /**
     * 模糊查询库位带库存
     *
     * @return bool|string
     */
    public function getPositionByStock(): bool|string
    {
        $val          = $this->post('keyword');//关键词
        $materialId          = $this->post('materialId');
        $warehouseId          = $this->post('warehouseId') ?: '#';
        $unit          = $this->post('unit');
        $zero          = $this->post('zero');
        $json['warn'] = 0;
        $json['data'] = [];

        /*
        $where            = " a.coid = '" . self::$coid . "' ";
        $like             = [
            'b.name' => $val,
        ];
        $equal            = [
            'a.materialId' => $materialId,
            'a.warehouseId' => $warehouseId,
        ];
        $where            .= search([
            "like" => $like,
            "="    => $equal,
        ]);
        $fieldArr         = self::resolveField([
            'field' => 'a.`positionId`, b.name, '.machiningOrderClass::material_num_change_sql('sum(a.num)','mat.unit','mat',$unit),
            'group' => 'a.positionId',
        ]);
        $where            .= $fieldArr['group'];
        $outAllowZero = optionSettingClass::getSettingItem('库存', 'outAllowZero');//允许零库存出库
        if(!$outAllowZero){
            $where .= " having num > 0 ";
        }
        $page = $this->page(array(
            'field' => $fieldArr['field'],
            "table" => 'warehouse_position as b left join inventory_record as a on a.positionId = b.id left join material as mat on a.materialId = mat.id',
            "where" => $where,
            "order" => ' sum(num) desc ',
        ));
        $json['pageAll'] = $page['para']['pageAll'];
        $json['sql'] = $page['sql'];

        foreach ($page['array'] as $val) {
            $json['data'][] = [
                'title'   => $val['name']."（".self::lostZero($val['num'],'numPrecision')."）",
                'id'      => $val['positionId'],
            ];
        }
        */
        $where            = " coid = '" . self::$coid . "' ";
        $like             = [
            'name' => $val,
        ];
        $equal            = [
            'orderId' => $warehouseId,
        ];
        $where            .= search([
            "like" => $like,
            "="    => $equal,
        ]);
        if(empty($zero)){
            $where .= " and (select IFNULL(sum(num), 0) from inventory_record where coid = '" . self::$coid . "' and materialId = '$materialId' and warehouseId = '$warehouseId' and positionId = warehouse_position.id ) > 0 ";
        }
        $page = $this->page(array(
            'field' => 'name,id',
            "table" => 'warehouse_position',
            "where" => $where,
            "order" => ' code ',
        ));
        $json['pageAll'] = $page['para']['pageAll'];
        $json['sql'] = $page['sql'];

        foreach ($page['array'] as $val) {
            $num = inventoryBalanceClass::inventoryNum($materialId, $warehouseId, $val['id']);
            $json['data'][] = [
                'title'   => $val['name']."（".self::lostZero($num,'numPrecision')."）",
                'id'      => $val['id'],
            ];
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    /** 获取批号
     * @param $materialId
     * @param string $warehouseId
     * @param string $positionId
     * @param string $unit
     * @return array
     */
    public static function getBatchOption($materialId, $warehouseId = '', $positionId = '', $unit = ''): array
    {
        if(empty($materialId) || empty($warehouseId)){
            return [];
        }
        $and = '';
        if($positionId){
            $and = " and positionId = '$positionId' ";
        }
        $where         = " 1=1 and materialId = '$materialId' and warehouseId = '$warehouseId' and coid = '" . self::$coid . "' {$and} ";
        $fieldArr      = self::resolveField([
            'field' => 'batch, SUM(num) as num',
            'group' => 'batch',
        ]);
        $where         .= $fieldArr['group'];
        $outAllowZero = optionSettingClass::getSettingItem('库存', 'outAllowZero');//允许零库存出库
        $having = "";
        if(!$outAllowZero){
            $having = " having SUM(num) > 0 ";
        }
        $result        = find([
            'table' => 'inventory_record',
            'field' => $fieldArr['field'],
            'where' => $where . $having." order by SUM(num) desc",
        ]);
        $batch = [];
        $mainUnit = self::getMainUnit($materialId);
        if(is_array($result['array'])){
            foreach ((array)$result['array'] as $k=>$array){
                if($unit) {
                    $array['num'] = machiningOrderClass::material_num_change($materialId, $mainUnit, $unit, $array['num']);
                }
                if($array['batch'] === ''){
                    $batch[''] = '无（'.self::lostZero($array['num'],'numPrecision').'）';
                }else{
                    $batch[$array['batch']] = $array['batch'].'（'.self::lostZero($array['num'],'numPrecision').'）';
                }
            }
        }
        if(!isset($batch['']))$batch[''] = '无（0）';
        return $batch;
    }

    /**
     * 模糊查询批次带库存
     *
     * @return bool|string
     */
    public function getBatchByStock(): bool|string
    {
        $val          = $this->post('keyword');//关键词
        $materialId          = $this->post('materialId');
        $warehouseId          = $this->post('warehouseId');
        $positionId          = $this->post('positionId');
        $unit          = $this->post('unit');
        $json['warn'] = 0;
        $json['data'] = [];

        $where            = " a.coid = '" . self::$coid . "' ";
        $like             = [
            'a.batch' => $val,
        ];
        $equal            = [
            'a.materialId' => $materialId,
            'a.warehouseId' => $warehouseId,
            'a.positionId' => $positionId,
        ];
        $where            .= search([
            "like" => $like,
            "="    => $equal,
        ]);
        $totalWhere = $where;
        $fieldArr         = self::resolveField([
            'field' => 'a.`batch`, '.machiningOrderClass::material_num_change_sql('sum(a.num)','mat.unit','mat',$unit),
            'group' => 'a.batch',
        ]);
        $where            .= $fieldArr['group'];
        $outAllowZero = optionSettingClass::getSettingItem('库存', 'outAllowZero');//允许零库存出库
        if(!$outAllowZero){
            $where .= " having num > 0 ";
        }
        $page = $this->page(array(
            'field' => $fieldArr['field'],
            "table" => 'inventory_record as a join material as mat on a.materialId = mat.id',
            "where" => $where,
            "order" => ' sum(num) desc ',
        ));
        $json['pageAll'] = $page['para']['pageAll'];
        if (empty($val) && static::total(['table' => 'inventory_record a', "where" => " {$totalWhere} and a.batch = ''  "]) == 0){
            $json['data'][] = [
                'title'   => "无（0）",
                'id'      => '',
            ];
        }
        foreach ($page['array'] as $val) {
            $json['data'][] = [
                'title'   => ($val['batch']?:'无')."（".self::lostZero($val['num'],'numPrecision')."）",
                'id'      => $val['batch'],
            ];
        }

        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    /** 根据仓库获取库位
     * @param string $warehouseId
     * @param string $materialId
     * @return mixed
     */
    public function getPosition($warehouseId = '', $materialId = ''): mixed
    {
        $warehouseId = $warehouseId ?: $this->post('warehouseId');
        $materialId = $materialId ?: $this->post('materialId');
        //批号
        $json['position'] = selectMultiple([
            "name" => "positionId[]",
            'option' => self::positionOption($materialId,$warehouseId),
            'title' => L('toolOverhaul.edit.choice'),
            'change' => 'getBatch',
            'value' => ''
        ]);
        return json_encode($json, 320);
    }

    /** 根据库位获取批次
     * @param string $warehouseId
     * @param string $positionId
     * @param string $materialId
     * @return mixed
     */
    public function getBatch($warehouseId = '', $positionId = '', $materialId = ''): mixed
    {
        $warehouseId = $warehouseId ?: $this->post('warehouseId');
        $positionId = $positionId ?: $this->post('positionId');
        $materialId = $materialId ?: $this->post('materialId');
        //批号
        $json['batch'] = selectMultiple([
            "name" => "batch[]",
            'option' => self::getBatchOption($materialId, $warehouseId, $positionId),
            'title' => L('toolOverhaul.edit.choice'),
            'change' => 'getStock',
            'value' => '-1'
        ]);
        return json_encode($json, 320);
    }
    /**
     * 根据批次获取库存
     */
    public function getStock(): bool|string
    {
        $warehouseId = $this->post('warehouseId');
        $positionId = $this->post('positionId');
        $materialId = $this->post('materialId');
        $batch = $this->post('batch');
        //批号
        $json['stock'] = inventoryBalanceClass::inventoryNum($materialId, $warehouseId, $positionId, $batch);
        return json_encode($json, 320);
    }



    /**
     * 选择仓库
     *
     * @return string
     */
    public static function chooseWarehouse(string $obj = '', string $callback = ''): string
    {
        $obj    = $obj ?: 'warehouseId';
        $result = find(array('table' => 'warehouse', 'where' => " coid = '" . self::$coid . "' AND state = '启用' ".self::getWarehouseSql()." order by time desc"));
        $li     = '';
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                $li .= "<li data-id='$array[id]'>{$array['name']}</li>";
            }
        }
        if (empty($li)) {
            $li = "<li>".L('toolOverhaul.chooseWarehouse.none')."</li>";
        }
        $batchWord = L('toolOverhaul.chooseWarehouse.batch');
        return <<<EOT
        <span class='del-row-button' id='chooseWareHouse'>$batchWord</span><div class='stateBlock' style="margin-top: 7px;"><ul>$li</ul></div>
        <script>
         //点击非下拉区域隐藏
        $(document).bind('click', function (e) {
            let target = $(".stateBlock");
            let obj = $(".warehouse");
            if(!target.is(e.target) && target.has(e.target).length ===0 && !obj.is(e.target) && obj.has(e.target).length ===0){
              target.hide();
            }
        });
        $("#chooseWareHouse").on('click',function() {
           $(".stateBlock").show();
        })
        $(".warehouse .stateBlock li").on('click',function() {
            let id = $(this).data('id');
            $("select[name='{$obj}[]']").each(function() {
              let obj = $(this);
              obj.val(id);
              $callback(this)
            });
           $(".stateBlock").hide();
        })
        </script>    
EOT;
    }

    public function editEdit()
    {
        $id               = $this->post('id') ?: self::getId();
        $mxIdArr          = $this->post('mxId') ?: [];
        $materialIdArr = $this->post('materialId');
        $warehouseArr     = $this->post('warehouseId');
        $positionArr     = $this->post('positionId');
        $numArr           = $this->post('num');
        $batchArr         = $this->post('batch');
        $typeArr         = $this->post('type');
        $priceArr         = $this->post('price');
        $moneyArr         = $this->post('money');

        $field            = [
            'factory' => $this->post('factory'),
            'orderDate'    => $this->post('orderDate'),
            'applicant' => $this->post('applicant'),
            'text'        => $this->post('text'),
        ];
        $annotation       = [
            'factory' => L('toolOverhaul.edit.factory'),
            'orderDate'    => L('toolOverhaul.edit.orderDate'),
            'applicant' => L('toolOverhaul.edit.applicant'),
            'text'        => L('toolOverhaul.edit.text'),
        ];
        $rules            = [
            'factory' => 'required',
            'orderDate' => 'required',
            'applicant' => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
            goto resp;
        }
        //同一物料同一库位批次不可重复添加
        $tempBatchResult = [];
        foreach ((array)$materialIdArr as $k=>$v) {
            if(isset($tempBatchResult[$v][$positionArr[$k]][$batchArr[$k]])){
                $json['warn'] = str_replace(['{{i}}'], [($k+1)], L('toolOverhaul.editEdit.repeat'));
                goto resp;
            }
            // 批次数量汇总
            $tempBatchResult[$v][$positionArr[$k]][$batchArr[$k]] = 1;
        }
        $where = " id = '$id' ";
        $info  = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('toolOverhaul.editEdit.power');
        } elseif (static::is_null_array($mxIdArr)) {
            $json['warn'] = L('toolOverhaul.editEdit.outMx');
        } elseif (static::is_null_array($materialIdArr)) {
            $json['warn'] = L('toolOverhaul.editEdit.outMx');
        } elseif (static::is_null_array($warehouseArr)) {
            $json['warn'] = L('toolOverhaul.editEdit.warehouse');
        } elseif (static::is_null_array($positionArr)) {
            $json['warn'] = L('toolOverhaul.editEdit.position');
        } elseif (static::is_null_array($numArr)) {
            $json['warn'] = L('toolOverhaul.editEdit.num');
        } elseif (!empty($info['id']) && $info['state'] != 0) {
            $json['warn'] = L('toolOverhaul.editEdit.stateError');
        } else {
            $this->startTrans();
            $isPass = true;//事务通过标志
            if (!$info['id']) {
                $orderNo      = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'JXCK' . date('Ymd'),
                    'table'  => self::table,
                    'field'  => 'orderNo',
                    'where'  => " AND coid = '" . self::$coid . "' ",
                ],$field);
                $field        = array_merge($field, [
                    'id'          => $id,
                    'orderNo'     => $orderNo,
                    'classify'       => 0,
                    'state'       => 0,
                    'maintenance_status'       => 0,
                    'coid'        => self::$coid,
                    'stid'        => $this->control['stid'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field,]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            //添加或更新报价单明细
            if (is_array($mxIdArr)) {
                foreach ($mxIdArr as $k => $nid) {
                    $mx          = query(self::tableMx, "id = '$nid'");
                    $material = query('material', "id = '$materialIdArr[$k]'","unit");
                    $numArr[$k] = self::formattingFigure($numArr[$k],'numPrecision');
                    if (!empty($mx['id'])) {
                        //更新
                        $warn = static::update([
                            "table" => self::tableMx,
                            "field" => [
                                'warehouseId'   => $warehouseArr[$k],
                                'positionId'   => $positionArr[$k],
                                'batch'         => $batchArr[$k],
                                'num'           => $numArr[$k],
                                'price'           => $priceArr[$k],
                                'money'           => $moneyArr[$k],
                                'type'           => $typeArr[$k],
                            ],
                            "where" => " id = '$nid'",
                        ]);
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => self::tableMx,
                            "field" => [
                                'id'            => $nid,
                                'coid'          => self::$coid,
                                'orderId'       => $id,
                                'materialId'    => $materialIdArr[$k],
                                'type'           => $typeArr[$k],
                                'batch'         => $batchArr[$k],
                                'num'           => $numArr[$k],
                                'price'           => $priceArr[$k],
                                'money'           => $moneyArr[$k],
                                'unit'          => $material['unit'],
                                'warehouseId'   => $warehouseArr[$k],
                                'positionId'   => $positionArr[$k],
                            ],
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass       = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
                $this->commitTrans();
                delete(['table' => self::tableMx, 'where' => " id not in ('" . implode("','", (array)$mxIdArr) . "') and orderId = '$id'"]);
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}','{{type}}','{{id}}'], [$this->control['name'],$type,$id], L('toolOverhaul.editEdit.log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * @return string
     */
    public function addMx(): string
    {
        $materialClassObj = new materialClass();
        $layerId = $this->get('cla') . ucwords($this->get('fun'));
        $formName = 'mxForm';
        $notAllowRepeat = '';
        $data = [
            'sub'=> " onclick=\"addRow();$('#" . $layerId . "').remove()\" ",
            'continueAdding'=> $notAllowRepeat?" onclick=\"addRow();removeSelectedContent('".$formName."')\" ":" onclick=\"addRow();\" ",
            'hidden'=> hidden(['name'=>'notAllowRepeat','value'=>$notAllowRepeat]),
        ];
        return $materialClassObj->addMx($data);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit()
    {
        $mxIdArr = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('toolOverhaul.addMxEdit.power');
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = L('toolOverhaul.addMxEdit.noChoice');
        } else {
            $tr = [];
            foreach ($mxIdArr as $mxId) {
                $material     = query('material', "id = '$mxId'");
                $id           = self::getId();
                $warehouseSel = select(array(
                    'name' => 'warehouseId[]',
                    'option' => self::warehouseOption($material['id']),
                    'change' => 'getPosition',
                    'title' => L('toolOverhaul.edit.warehouse'),
                    'value' => ''
                ));
                $position = selectMultiple([
                    "name" => "positionId[]",
                    'option' => self::positionOption($material['id'],'##'),
                    'title' => L('toolOverhaul.edit.choice'),
                    'change' => 'getBatch',
                    'value' => ''
                ]);
                $batch = selectMultiple([
                    "name" => "batch[]",
                    'option' => self::getBatchOption($material['id'], '', ''),
                    'title' => L('toolOverhaul.edit.choice'),
                    'change' => 'getStock',
                    'value' => ''
                ]);
                $price        = text(['name' => 'price[]', 'blur' => 'countMoney', 'other' => self::digitalFiltering('pricePrecision')]);
                $money        = text(['name' => 'money[]', 'blur' => 'countMoney', 'other' => self::digitalFiltering()]);
                $type        = select(["name" => "type[]", 'option' => explode('，',para('maintenancestateType')), 'value' => '', 'title' => '{l.toolOverhaul.edit.type}']);
                $tr[]        =
                    [
                        componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                        hidden(['name' => 'mxId[]', 'value' => $id]) .
                        hidden(['name' => 'materialId[]', 'value' => $mxId]),
                        $material['code'],
                        $material['name'],
                        $material['model'],
                        $material['unit'],
                        $warehouseSel,
                        "<span class='position'>$position</span>",
                        "<span class='batch'>$batch</span>",
                        "<span class='stock'></span>",
                        $type,
                        text(['name' => 'num[]', 'blur' => 'countMoney', 'value' => '', 'other' => self::digitalFiltering('numPrecision')]),
                        $price,
                        $money,
                    ];
            }
            $json['html'] = $this->tableMany(array('tr' => $tr, 'thead' => false));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " coid = '" . self::$coid . "' AND id = '{$this->get('id')}' ");
        if (empty($info['id'])) {
            $html = L('toolOverhaul.detail.empty');
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );

            $button = [];
            if ($this->power(self::page, "edit") && $info['state'] == 0) {
                //按钮
                $button[] = [
                    "name" => L('toolOverhaul.homeSearch.del'),
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
                //按钮
                $button[] = [
                    "name"  => L('toolOverhaul.detail.edit'),
                    "type"  => "顶部页卡",
                    "title" => L('toolOverhaul.detail.editDetail'),
                    "url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                    'style' => 'li-btn-blue-bg',
                ];
                $button[] = [
                    "name"  => L('toolOverhaul.detail.sureOut'),
                    "type"  => "弹出层",
                    "cla"   => $this->get('cla'),
                    "fun"   => "operate",
                    "post"  => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            //操作记录
            $button[] = self::operateLogBut($info['id'],1);

            $mxtr[] = ['{l.toolOverhaul.detail.code}', '{l.toolOverhaul.detail.name}', '{l.toolOverhaul.detail.model}', '{l.toolOverhaul.detail.unit}', '{l.toolOverhaul.detail.warehouse}', '{l.toolOverhaul.edit.position}', '{l.toolOverhaul.detail.batch}', '{l.toolOverhaul.detail.num}', '{l.toolOverhaul.detail.type}', '{l.toolOverhaul.detail.price}', '{l.toolOverhaul.detail.money}'];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($result['array'] as $array) {
                $material    = query('material', " id = '$array[materialId]'");
                $mxtr[]      = [
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    warehouseClass::getName($array['warehouseId']),
                    warehousePositionClass::getName($array['positionId']),
                    $array['batch'],
                    self::lostZero($array['num'],'numPrecision'),
                    $array['type'],
                    self::lostZero($array['price'],'pricePrecision'),
                    self::lostZero($array['money']),
                ];
            }
            $total_tr = [
                7 => self::lostZero(array_sum(array_column($result['array'],'num')), 'numPrecision'),
                10 => self::lostZero(array_sum(array_column($result['array'],'money'))),
            ];
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow([
                '详细信息' => [
                    [
                        L('toolOverhaul.detail.factory') => $info['factory'],
                        L('toolOverhaul.detail.orderDate')  => $info['orderDate'],
                        L('toolOverhaul.detail.applicant') => self::findStaff($info['applicant']),
                        L('toolOverhaul.detail.orderNo') => $info['orderNo'],
                    ],
                    [
                        L('toolOverhaul.detail.stid')  => self::findStaff($info['stid']),
                        L('toolOverhaul.detail.state')   => self::state[$info['state']]
                    ],
                    [
                        L('toolOverhaul.detail.text') => pre($info['text']),
                    ],
                ],
            ]);
            $data['html'] .= $this->detailList([
                'title' => L('toolOverhaul.detail.overhaulMx'),
                'html' => $this->listTable(array('tr' => $mxtr, 'showSort' => true, 'total' => $total_tr)),
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id    = $this->post('id');
        $info  = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
        $field = [
            'state' => 1,
            'confirmTime' => $this->time
        ];
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('toolOverhaul.confirmEdit.power');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('toolOverhaul.confirmEdit.empty');
        } elseif ($info['state'] != 0) {
            $json['warn'] = L('toolOverhaul.confirmEdit.stateError');
        } else {
            $this->startTrans();
            $isPass = true; // 事务通过标志

            $json['warn'] = update([
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ]);
            if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass === true) {
                $details = find([
                    'table' => self::tableMx,
                    'where' => " orderId = '{$info['id']}'",
                ]);
                /***仓库允许零库存出库*/
                $outAllowZero = optionSettingClass::getSettingItem('库存','outAllowZero');
                foreach ($details['array'] as $key => $value) {
                    // 转换主单位
                    $mainUnitNum = inventoryBalanceClass::toMainUnit($value['materialId'], $value['num'], $value['unit']);
                    $stock = inventoryBalanceClass::inventoryNum($value['materialId'], $value['warehouseId'], $value['positionId'], $value['batch']);
                    $bool = inventoryBalanceClass::inventoryControl($value['materialId'], $mainUnitNum, "down");  //最低库存控制
                    if($bool !== true){
                        $json['warn'] = $bool;
                        goto resp;
                    }
                    // 判断库存
                    if (!$outAllowZero && $stock - $mainUnitNum < 0) {
                        $json['warn'] = L('toolOverhaul.confirmEdit.transfinite');
                        goto resp;
                    }elseif($outAllowZero && $stock - $mainUnitNum < 0){
                        //发送负库存预警
                        $setting = self::getSettingValue('inventoryNegative');
                        foreach ($setting['member'] as $item) {
                            message(array(
                                "stid" => $item,
                                "type" => '预警消息',
                                "typeId" => $value['materialId'],
                                "text" => "物料【".materialClass::getName($value['materialId'])."】负库存预警",
                                "targetCla" => 'inventoryBalance',
                                "targetFun" => 'detail',
                            ));
                        }
                    }
                }
                /***生成出库明细***/
                $bool = $this->insertInventoryOut($info);
                if($bool !== true){
                    $json['warn'] = $bool;
                    goto resp;
                }
                $this->commitTrans();//提交事务
                auditingFollow(array(
                    "type"   => "工具检修出库单",
                    "typeId" => $info['id'],
                    "text"   => "【{$this->control['name']}】确认",
                ));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}','{{type}}','{{id}}'], [$this->control['name'],$type,$id], lang('toolOverhaul.confirmEdit.log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 生成出库单
     */
    private function insertInventoryOut($info): bool|string
    {
        $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"));
        $id = self::getId();
        $field = [
            'id' => $id,
            'coid' => self::$coid,
            'orderNo' => codeTemplateClass::generateCode('outStock', [
                'prefix' => 'CKD' . date('Ymd'),
                'table' => 'inventory_changes',
                'field' => 'orderNo',
                'where' => " and coid = '" . self::$coid . "'",
            ], []),
            'type' => '其他出库',
            'classify' => 0,
            'recordDate' => $this->date,
            'confirmTime' => $this->date,
            'reviewTime' => $this->date,
            'state' => '已复核',
            'stid' => self::$stid,
        ];
        $warn = static::insert(array(
            'table' => 'inventory_changes',
            'field' => $field
        ));
        if ($warn != '新增成功') {
            return "新增出库单失败";
        }
        foreach ($result['array'] as $mx) {
            $warn = static::insert(array(
                'table' => 'inventory_changes_detail',
                'field' => $fieldChangeMx = [
                    'id' => self::getId(),
                    'coid' => self::$coid,
                    'orderId' => $id,
                    'materialId' => $mx['materialId'],
                    'orderNum' => $mx['num'],
                    'batch' => $mx['batch'],
                    'num' => $mx['num'],
                    'unit' => $mx['unit'],
                    'price' => $mx['price'],
                    'money' => $mx['money'],
                    'sourceTable' => 'tool_overhaul_detail',
                    'sourceId' => $mx['id'],
                    'sourceNo' => $info['orderNo'],
                    'warehouseId' => $mx['warehouseId'],
                    'positionId' => $mx['positionId'],
                ]
            ));
            if ($warn != '新增成功') {
                return "新增出库单明细失败";
            }
            // 转换主单位
            $mainUnitNum = inventoryBalanceClass::toMainUnit($mx['materialId'], $mx['num'], $mx['unit']);
            $warn = insert([
                'table' => self::tableRecord,
                'field' => [
                    'id'            => self::getNo(),
                    'coid'          => self::$coid,
                    'warehouseId'   => $mx['warehouseId'],
                    'positionId'    => $mx['positionId'],
                    'materialId'    => $mx['materialId'],
                    'batch'         => $mx['batch'],
                    'num'           => -1 * $mainUnitNum,
                    'changesId' => $fieldChangeMx['id'],
                ],
            ]);
            if (!empty($mx['positionId']) && $warn == '新增成功') {
                inventoryBalanceClass::recordStockToLocation('', ['materialId' => $mx['materialId'], 'warehouseId' => $mx['warehouseId'], 'positionId' => $mx['positionId'], 'batch' => $mx['batch']]);
            }
            if ($warn != '新增成功') {
                return "新增出库记录失败";
            }
        }
        return true;
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $id     = $this->post('id') ?? '';
        $pwd = $word = $height = false; // 需要密码
        $append = [];
        switch ($act) {
            case 'confirm':
                $act      = 'edit';
                $msg      = L('toolOverhaul.operate.sure');
                $title    = L('toolOverhaul.operate.sureTitle');
                $function = 'confirmEdit';
                $form     = self::page . 'OperateForm, detailForm';
                $power    = '';
                $word     = true;
                break;
            default:
                $act      = 'del';
                $msg      = L('toolOverhaul.operate.del');
                $title    = self::page . 'Delete';
                $function = 'delete';
                $form     = self::page . 'OperateForm, listForm, quoForm';
                $power    = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], lang('toolOverhaul.operate.log'));;
            $json             = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
                'word'     => $word,
                'append'   => $append,
                'height'   => $height,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     *
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('toolOverhaul.delete.power');
        } elseif (empty($array)) {
            $json['warn'] = L('toolOverhaul.delete.noChoice');
        } else {
            $text  = "";
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id' ");
                if ($info['state'] != 0) {
                    $warn = L('toolOverhaul.delete.fail');
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    delete(array("table" => 'auditing_follow', "where" => " typeId = '$id' "));
                    //返回
                    $warn = L('toolOverhaul.delete.success');
                    $x++;
                }
                $text .= str_replace(['{{id}}'], [$info['id']], lang('toolOverhaul.delete.text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], lang('toolOverhaul.delete.log')). "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], lang('toolOverhaul.delete.warn'));
            $json['warn']     = 2;
            $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 打印
     *
     * @return string
     */
    public function printPage($param = '', $isReturn = true): string|array
    {
        $id                  = $param ?: $this->get('id');
        $info                = query(static::table, " id = '$id'");
        $info['companyName'] = query('company', "coid = '" . static::$coid . "'")['name']; //公司名称
        $info['title']       = static::title;
        $info['printTime']   = $this->time;
        $info['stid']        = static::findStaff($info['stid']);
        $info['orderDate']   = date('Y/m/d', strtotime($info['time']));
        $detail              = find(['table' => static::tableMx, 'where' => "orderId = '$info[id]' order by list asc"])['array'];
        $items               = [];
        $x                   = 1;
        $totalNum            = $totalMoney = 0;
        foreach ($detail as $array) {
            $material    = query('material', "id = '$array[materialId]'");
            $items[]     = [
                'no'              => $x,
                'materialCode'    => $material['code'],
                'materialName'    => $material['name'],
                'warehouse'       => warehouseClass::getName($array['warehouseId']),
                'position'        => warehousePositionClass::getName($array['positionId']),
                'model'           => $material['model'],
                'unit'            => $array['unit'],
                'batch'           => $array['batch'],
                'type'            => $array['type'],
                'num'             => static::lostZero($array['num'], 'numPrecision'),
            ];
            $x++;
            $totalNum += floatval($array['num']);
        }
        $append         = [
            'no'  => L('outStockExec.printPage.total'),
            'num' => static::lostZero($totalNum, 'numPrecision'),
        ];
        $items[]        = $append;
        $info['detail'] = $items;
        if ($isReturn) {
            return (new printTemplateClass())->start(static::page, $info);
        } else {
            return $info;
        }
    }

    /*列表页-查询条件*/
    public function toolOverhaulRecordOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('toolOverhaul.home.orderNo') => text(array("name" => "orderNo")),
                    L('toolOverhaul.edit.type')   => select(["name" => "type", 'option' => explode('，',para('maintenancestateType'))]),
                    L('toolOverhaul.addMx.code') => text(["name" => "code"]),
                ],
                [
                    L('toolOverhaul.addMx.name') => text(["name" => "name"]),
                    L('toolOverhaul.addMx.model') => text(["name" => "model"]),
                    L('toolOverhaul.detail.batch') => text(["name" => "batch"]),
                ],
                [
                    L('toolOverhaul.edit.orderDate') => text(['name' => 'orderDate', 'laydate' => ['range' => '~', 'type' => 'date']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-工具检修记录-查询条件*/
    public function toolOverhaulRecord()
    {
        $html = $this->toolOverhaulRecordOptions(false);
        //控件
        $button = "";
        if ($this->power('toolOverhaulRecord', "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }



    /*客户列表-查询结果*/
    public function toolOverhaulRecordSearch()
    {
        //查询结果
        $where = " a.coid = '" . self::$coid . "' and b.classify = 0 and b.state = 1 ";
        $equal = [
            'a.type' => $this->post('type'),
        ];
        $like  = [
            'b.orderNo' => $this->post('orderNo'),
            'm.name' => $this->post('name'),
            'code'   => $this->post('code'),
            'model'  => $this->post('model'),
            'a.batch'  => $this->post('batch'),
        ];
        //生成查询语句
        $where .= search([
            "="    => $equal,
            "like" => $like,
        ]);
        if ($this->post('orderDate')) {
            $where .= self::timeComparison($this->post('orderDate'), 'date', 'b.orderDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'a.time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page    = $this->page(array(
            "table" => self::tableMx." as a join ".self::table." as b on a.orderId = b.id join material as m on a.materialId = m.id",
            "field" => "a.*,b.orderNo,b.orderDate,m.code,m.name",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION['toolOverhaulRecord']['sql'] = $page['sql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'num':
                        $row[] = self::lostZero($array['num'],'numPrecision');
                        break;
                    case 'return_num':
                        $row[] = self::lostZero($array['return_num'],'numPrecision');
                        break;
                    case 'not_return_num':
                        $row[] = self::formattingFigure($array['num']-$array['return_num']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::tableMx." as a join ".self::table." as b on a.orderId = b.id join material as m on a.materialId = m.id",
            'single' => $where,
            'field'  => "ifnull(sum(a.num),0) as num,ifnull(sum(a.return_num),0) as return_num",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
            'return_num'   => self::lostZero($totalQuery['return_num'], 'numPrecision'),
            'not_return_num' => self::formattingFigure($totalQuery['num']-$totalQuery['return_num']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power('toolOverhaulRecord', 'export')) {
            $_SESSION['warn'] = L('toolOverhaul.homeSearch.power');
        }else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::tableMx." as a join ".self::table." as b on a.orderId = b.id join material as m on a.materialId = m.id",
                    "field" => "a.*,b.orderNo,b.orderDate,m.code,m.name",
                    "where" => "a.id in ('".implode("','", $checkedId)."') order by a.time desc",
                ))['array'];
            }else{
                $sql    = $_SESSION['toolOverhaulRecord']['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '单据编号'=>$array['orderNo'],
                            '检修类型'=>$array['type'],
                            '物料编码'=>$array['code'],
                            '物料名称'=>$array['name'],
                            '单位'=>$array['unit'],
                            '检修数量'=> self::lostZero($array['num'],'numPrecision'),
                            '供应商返还数量'=> self::lostZero($array['return_num'],'numPrecision'),
                            '未返还数量'=>self::lostZero($array['num']-$array['return_num'],'numPrecision'),
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }

            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('toolOverhaul.homeSearch.log'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, self::title . ".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }
    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'单据编号',
                    'aliasName'=>'单据编号',
                ],
                [
                    'columnName'=>'检修类型',
                    'aliasName'=>'检修类型',
                ],
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',
                ],
                [
                    'columnName'=>'检修数量',
                    'aliasName'=>'检修数量',
                ],
                [
                    'columnName'=>'供应商返还数量',
                    'aliasName'=>'供应商返还数量',
                ],
                [
                    'columnName'=>'未返还数量',
                    'aliasName'=>'未返还数量',
                ],
            ]
        };
    }
}
